package com.sunday.scoremanager.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.event.EventBus;
import com.sunday.common.event.ExitApp;
import com.sunday.common.imageselector.MultiImageSelectorActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.CacheUtils;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.ImageUtils;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.utils.UploadUtils;
import com.sunday.common.widgets.CircleImageView;
import com.sunday.common.widgets.UIAlertEditView;
import com.sunday.scoremanager.R;
import com.sunday.scoremanager.base.BaseApp;
import com.sunday.scoremanager.entity.Member;
import com.sunday.scoremanager.entity.UpLoadImg;
import com.sunday.scoremanager.http.ApiClient;

import java.io.File;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/10/26.
 */

public class SettingActivity extends BaseActivity {

    @Bind(R.id.left_btn)
    ImageView leftBtn;
    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.rightTxt)
    TextView rightTxt;
    @Bind(R.id.right_btn)
    ImageView rightBtn;
    @Bind(R.id.common_header)
    RelativeLayout commonHeader;
    @Bind(R.id.menu_clear_cash)
    TextView menuClearCash;
    @Bind(R.id.btn_logout)
    TextView btnLogout;

    @Bind(R.id.user_logo)
    CircleImageView userLogo;
    @Bind(R.id.user_name)
    TextView userName;
    @Bind(R.id.user_mobile)
    TextView userMobile;
    @Bind(R.id.menu_user_pwd)
    LinearLayout menuUserPwd;
    @Bind(R.id.menu_about_us)
    TextView menuAboutUs;
    @Bind(R.id.menu_user_pay_pwd)
    LinearLayout menuUserPayPwd;

    private Member member;
    private long memberId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        ButterKnife.bind(this);
        titleView.setText("设置");
        member = BaseApp.getInstance().getMember();
        memberId = member.getSellerId();
        menuClearCash.setText("清理缓存  （" + CacheUtils.getTotalCacheSize(mContext) + "）");
        initView();
    }


    private void initView() {
        if (!TextUtils.isEmpty(member.getLogo())) {
            Glide.with(mContext)
                    .load(member.getLogo())
                    .error(R.mipmap.ic_default)
                    .into(userLogo);
        }
        userName.setText(TextUtils.isEmpty(member.getShopName()) ? "" : member.getShopName());
        userMobile.setText(member.getLinkPhone());
        userMobile.setVisibility(member.getPermission() != 1 ? View.GONE : View.VISIBLE);
        menuUserPayPwd.setVisibility(member.getPermission() != 1 ? View.GONE : View.VISIBLE);
    }

    private final static int REQUEST_IMAGE = 0x1111;

    @OnClick({R.id.menu_clear_cash, R.id.btn_logout, R.id.menu_user_logo, R.id.menu_user_name, R.id.menu_user_pwd,
            R.id.menu_about_us, R.id.menu_user_pay_pwd})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.menu_clear_cash:
                CacheUtils.clearAllCache(mContext);
                menuClearCash.setText("清理缓存  （" + CacheUtils.getTotalCacheSize(mContext) + "）");
                break;
            case R.id.btn_logout:
                showLogoutDialog();
                break;
            case R.id.menu_user_logo:
                intent = new Intent(mContext, MultiImageSelectorActivity.class);
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
                startActivityForResult(intent, REQUEST_IMAGE);
                break;
            case R.id.menu_user_name:
                final UIAlertEditView alertView = new UIAlertEditView(mContext, "修改昵称", "请输入新昵称", "取消", "确定", member.getNickName());
                alertView.show();
                alertView.setClicklistener(new UIAlertEditView.ClickListenerInterface() {
                    @Override
                    public void doLeft() {
                        alertView.dismiss();
                    }

                    @Override
                    public void doRight() {
                        String name = alertView.getContent();
                        if (TextUtils.isEmpty(name)) {
                            ToastUtils.showToast(mContext, "请输入具体名字");
                            return;
                        }
                        saveInfo(null, name);
                        alertView.dismiss();
                    }
                });
                break;
            case R.id.menu_user_pwd:
                intent = new Intent(mContext, RegisterActivity.class);
                intent.putExtra("type", 1);
                startActivity(intent);
                break;
            case R.id.menu_about_us:
                intent = new Intent(mContext, AboutUsActivity.class);
                startActivity(intent);
                break;
            case R.id.menu_user_pay_pwd:
                intent = new Intent(mContext, SettingPayPwdActivity.class);
                intent.putExtra("type", 1);
                startActivity(intent);
                break;
        }
    }

    private void showLogoutDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("温馨提示");
        builder.setMessage("退出登录？");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                SharePerferenceUtils.getIns(mContext).removeKey("oAuth");
                SharePerferenceUtils.getIns(mContext).removeKey(Constants.IS_LOGIN);
                SharePerferenceUtils.getIns(mContext).removeKey(Constants.MEMBERID);
                EventBus.getDefault().post(new ExitApp());
                intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);
                finish();
                //deleteClientId();

            }
        });
        builder.show();

    }

    private void saveInfo(String logo, String name) {
        showLoadingDialog(0);
        Call<ResultDO<Member>> call = ApiClient.getApiAdapter().updateMember(memberId, logo, name);
        call.enqueue(new Callback<ResultDO<Member>>() {
            @Override
            public void onResponse(Call<ResultDO<Member>> call, Response<ResultDO<Member>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                if (response.body().getCode() == 0) {
                    member = response.body().getResult();
                    SharePerferenceUtils.getIns(mContext).saveOAuth(member);
                    BaseApp.getInstance().setMember(member);
                    initView();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Member>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    private ArrayList<String> mSelectPath = new ArrayList<>();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        mSelectPath.clear();
        mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
        if (mSelectPath != null) {
            String logo = ImageUtils.getCompressImagePath(mSelectPath.get(0));
            Glide.with(mContext)
                    .load(new File(logo))
                    .placeholder(R.mipmap.ic_default)
                    .error(R.mipmap.ic_default)
                    .into(userLogo);
            uploadImg(UploadUtils.getRequestBody(logo));
        }

    }

    private void uploadImg(final RequestBody requestBody) {
        showLoadingDialog(0);
        Call<ResultDO<UpLoadImg>> call
                = ApiClient.getApiAdapter().singleImage(requestBody);
        call.enqueue(new Callback<ResultDO<UpLoadImg>>() {
            @Override
            public void onResponse(Call<ResultDO<UpLoadImg>> call, Response<ResultDO<UpLoadImg>> response) {
                dissMissDialog();
                if (response.body() == null || isFinish) {
                    return;
                }
                if (response.body() != null && response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext, "上传成功");
                    String img = response.body().getResult().getViewUrl();
                    saveInfo(img, null);
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<UpLoadImg>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, "网络错误");
            }
        });
    }


    private void deleteClientId() {
        //showLoadingDialog(0);
        /*Call<ResultDO> call= ApiClient.getApiAdapter().deleteClientId(BaseApplication.getInstance().getMember().getId());
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (isFinish||response.body()==null){return;}
                dissMissDialog();
                if (response.body().getCode()==0){
                    EventBus.getDefault().post(new ExitApp());
                    intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                    finish();
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {

            }
        });*/
    }
}
